package com.agricultural.machine;

import com.agricultural.machine.chain.SafetyEvent;
import com.agricultural.machine.chain.SafetyManager;
import com.agricultural.machine.command.MachineTaskCommand;
import com.agricultural.machine.command.TaskCommand;
import com.agricultural.machine.command.TaskManager;
import com.agricultural.machine.common.AbstractMachine;
import com.agricultural.machine.common.IMachine;
import com.agricultural.machine.decorator.MachineDecoratorFactory;
import com.agricultural.machine.environment.EnvironmentData;
import com.agricultural.machine.environment.EnvironmentMonitor;
import com.agricultural.machine.factory.MachineFactory;
import com.agricultural.machine.logging.LogLevel;
import com.agricultural.machine.logging.Logger;
import com.agricultural.machine.messaging.Message;
import com.agricultural.machine.messaging.MessageBroker;
import com.agricultural.machine.monitoring.SystemMonitor;
import com.agricultural.machine.path.PathOptimizer;
import com.agricultural.machine.path.PathPoint;
import com.agricultural.machine.path.TerrainData;
import com.agricultural.machine.proxy.IMachineProxy;
import com.agricultural.machine.proxy.MachineProxyFactory;
import com.agricultural.machine.user.User;
import com.agricultural.machine.user.UserManager;
import com.agricultural.machine.user.UserRole;
import com.agricultural.machine.user.UserSession;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Random;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;


public class AgriculturalSystem {
    private final Logger logger;
    private final MachineFactory machineFactory;
    private final MachineProxyFactory proxyFactory;
    private final TaskManager taskManager;
    private final SafetyManager safetyManager;
    private final PathOptimizer pathOptimizer;
    private final UserManager userManager;
    private final SystemMonitor systemMonitor;
    private boolean running = false;

    public AgriculturalSystem() {
        this.logger = Logger.getInstance();
        this.machineFactory = MachineFactory.getInstance();
        this.proxyFactory = MachineProxyFactory.getInstance();
        this.taskManager = TaskManager.getInstance();
        this.safetyManager = SafetyManager.getInstance();
        this.pathOptimizer = PathOptimizer.getInstance();
        this.userManager = UserManager.getInstance();
        this.systemMonitor = SystemMonitor.getInstance();

        logger.setLogLevel(LogLevel.INFO);
    }


    public void initialize() {
        logger.info("AgriculturalSystem", "农业机械智能系统初始化中...");

        // 初始化各个组件
        systemMonitor.getInstance(); // 确保系统监控已启动

        // 创建不同类型的农机
        createDefaultMachines();

        logger.info("AgriculturalSystem", "系统初始化完成");
    }


    private void createDefaultMachines() {
        // 使用代理模式创建不同类型的农机
        for (String type : new String[]{"tractor", "harvester", "seeder", "sprayer"}) {
            IMachineProxy proxy = proxyFactory.createMachineProxy(type);
            IMachine machine = MachineDecoratorFactory.createLoggedMachine(proxy.getMachine());
            logger.info("AgriculturalSystem", String.format("已创建农机: ID=%s, 类型=%s",
                    machine.getMachineId(), machine.getType()));
        }
    }


    public void start() {
        running = true;
        System.out.println("    〖 智能农场管理系统 〗    ");

        // 启动菜单界面
        startMenuInterface();
    }


    private void startMenuInterface() {
        Scanner scanner = new Scanner(System.in);

        while (running) {
            displayMainMenu();
            System.out.print("请选择操作: ");
            String input = scanner.nextLine().trim();

            try {
                int choice = Integer.parseInt(input);
                processMenuChoice(choice, scanner);
            } catch (NumberFormatException e) {
                System.out.println("请输入有效的数字选项!");
            }
        }

        scanner.close();
    }


    private void displayMainMenu() {
        System.out.println("\n   〖 智能农场管理系统 〗   ");
        System.out.println("1. 查看设备列表 ");
        System.out.println("2. 添加新设备 ");
        System.out.println("3. 操作设备 ");
        System.out.println("4. 模拟环境数据 ");
        System.out.println("5. 路径规划 ");
        System.out.println("6. 用户管理");
        System.out.println("7. 系统管理 ");
        System.out.println("8. 退出 ");
    }


    private void processMenuChoice(int choice, Scanner scanner) {
        switch (choice) {
            case 1:
                // 检查用户是否已登录
                if (!checkLoggedIn()) {
                    return;
                }
                listMachines();
                break;
            case 2:
                // 检查用户是否已登录
                if (!checkLoggedIn()) {
                    return;
                }
                showAddDeviceMenu(scanner);
                break;
            case 3:
                // 检查用户是否已登录
                if (!checkLoggedIn()) {
                    return;
                }
                showOperateDeviceMenu(scanner);
                break;
            case 4:
                // 检查用户是否已登录
                if (!checkLoggedIn()) {
                    return;
                }
                monitorEnvironment(scanner);
                break;
            case 5:
                // 检查用户是否已登录
                if (!checkLoggedIn()) {
                    return;
                }
                showPathPlanningMenu(scanner);
                break;
            case 6:
                // 添加用户管理功能
                showUserManagementMenu(scanner);
                break;
            case 7:
                // 检查用户是否已登录
                if (!checkLoggedIn()) {
                    return;
                }
                showSystemManagementMenu(scanner);
                break;
            case 8:
                running = false;
                System.out.println("正在安全关闭系统...");
                break;
            default:
                System.out.println("无效选项，请重新选择!");
        }
    }


    private boolean checkLoggedIn() {
        UserSession session = userManager.getCurrentSession();
        if (session == null) {
            System.out.println("您尚未登录，请先登录系统。");
            System.out.println("请在用户管理菜单中选择登录选项。");
            return false;
        }
        return true;
    }


    private void showUserManagementMenu(Scanner scanner) {
        System.out.println("\n—————— 用户管理 ——————");
        System.out.println("1. 用户登录");
        System.out.println("2. 用户注销");
        System.out.println("3. 列出所有用户");
        System.out.println("4. 添加新用户");
        System.out.println("5. 修改用户角色");
        System.out.println("6. 返回主菜单");
        System.out.print("请选择: ");

        try {
            int choice = Integer.parseInt(scanner.nextLine().trim());

            switch (choice) {
                case 1:
                    System.out.print("请输入用户名: ");
                    String username = scanner.nextLine().trim();
                    System.out.print("请输入密码: ");
                    String password = scanner.nextLine().trim();
                    loginUser(username, password);
                    break;
                case 2:
                    logoutUser();
                    break;
                case 3:
                    listUsers();
                    break;
                case 4:
                    if (!userManager.hasPermission(UserRole.ADMIN)) {
                        System.out.println("权限不足，需要管理员权限");
                        return;
                    }
                    System.out.print("请输入用户名: ");
                    String newUser = scanner.nextLine().trim();
                    System.out.print("请输入密码: ");
                    String newPass = scanner.nextLine().trim();
                    System.out.print("请输入角色(ADMIN/OPERATOR/VIEWER): ");
                    String role = scanner.nextLine().trim();
                    addUser(newUser, newPass, role);
                    break;
                case 5:
                    if (!userManager.hasPermission(UserRole.ADMIN)) {
                        System.out.println("权限不足，需要管理员权限");
                        return;
                    }
                    System.out.print("请输入用户名: ");
                    String targetUser = scanner.nextLine().trim();
                    System.out.print("请输入新角色(ADMIN/OPERATOR/VIEWER): ");
                    String newRole = scanner.nextLine().trim();
                    changeUserRole(targetUser, newRole);
                    break;
                case 6:
                    return;
                default:
                    System.out.println("无效选项!");
            }

        } catch (NumberFormatException e) {
            System.out.println("请输入有效的数字选项!");
        }
    }


    private void loginUser(String username, String password) {
        boolean success = userManager.login(username, password).isPresent();
        if (success) {
            UserSession session = userManager.getCurrentSession();
            System.out.println("登录成功! 欢迎 " + username + " (" + session.getRole().getDescription() + ")");
        } else {
            System.out.println("登录失败，用户名或密码错误");
        }
    }


    private void logoutUser() {
        UserSession session = userManager.getCurrentSession();
        if (session != null) {
            String username = session.getUsername();
            userManager.logout();
            System.out.println("已注销用户: " + username);
        } else {
            System.out.println("您尚未登录");
        }
    }


    private void showAddDeviceMenu(Scanner scanner) {
        System.out.println("\n—————— 添加新设备 ——————");
        System.out.println("1. 添加拖拉机");
        System.out.println("2. 添加收割机");
        System.out.println("3. 添加播种机");
        System.out.println("4. 添加喷洒机");
        System.out.println("5. 返回主菜单");
        System.out.print("请选择: ");

        try {
            int choice = Integer.parseInt(scanner.nextLine().trim());
            String type = null;

            switch (choice) {
                case 1:
                    type = "tractor";
                    break;
                case 2:
                    type = "harvester";
                    break;
                case 3:
                    type = "seeder";
                    break;
                case 4:
                    type = "sprayer";
                    break;
                case 5:
                    return;
                default:
                    System.out.println("无效选项!");
                    return;
            }

            System.out.print("请输入设备描述: ");
            String description = scanner.nextLine().trim();
            addMachine(type, description);

        } catch (NumberFormatException e) {
            System.out.println("请输入有效的数字选项!");
        }
    }


    private void showOperateDeviceMenu(Scanner scanner) {
        System.out.println("\n—————— 操作设备 ——————");
        System.out.println("1. 启动设备");
        System.out.println("2. 停止设备");
        System.out.println("3. 执行设备任务");
        System.out.println("4. 更新设备位置");
        System.out.println("5. 紧急停止设备");
        System.out.println("6. 解除紧急停止");
        System.out.println("7. 返回主菜单");
        System.out.print("请选择: ");

        try {
            int choice = Integer.parseInt(scanner.nextLine().trim());

            if (choice == 7) {
                return;
            }

            // 获取设备ID
            listMachines();
            System.out.print("请输入设备ID: ");
            String machineId = scanner.nextLine().trim();

            switch (choice) {
                case 1:
                    startMachine(machineId);
                    break;
                case 2:
                    stopMachine(machineId);
                    break;
                case 3:
                    System.out.print("请输入任务描述: ");
                    String taskDesc = scanner.nextLine().trim();
                    executeTask(machineId, taskDesc);
                    break;
                case 4:
                    try {
                        System.out.print("请输入X坐标: ");
                        double x = Double.parseDouble(scanner.nextLine().trim());
                        System.out.print("请输入Y坐标: ");
                        double y = Double.parseDouble(scanner.nextLine().trim());
                        updateMachinePosition(machineId, x, y);
                    } catch (NumberFormatException e) {
                        System.out.println("请输入有效的坐标值!");
                    }
                    break;
                case 5:
                    emergencyStop(machineId);
                    break;
                case 6:
                    releaseEmergencyStop(machineId);
                    break;
                default:
                    System.out.println("无效选项!");
            }

        } catch (NumberFormatException e) {
            System.out.println("请输入有效的数字选项!");
        }
    }


    private void showPathPlanningMenu(Scanner scanner) {
        System.out.println("\n—————— 路径规划 ——————");
        System.out.println("1. 设置路径规划策略");
        System.out.println("2. 优化设备路径");
        System.out.println("3. 返回主菜单");
        System.out.print("请选择: ");

        try {
            int choice = Integer.parseInt(scanner.nextLine().trim());

            switch (choice) {
                case 1:
                    System.out.println("可用策略: direct, avoidObstacle, terrainOptimized");
                    System.out.print("请输入策略名称: ");
                    String strategy = scanner.nextLine().trim();
                    setPathStrategy(strategy);
                    break;
                case 2:
                    listMachines();
                    System.out.print("请输入设备ID: ");
                    String machineId = scanner.nextLine().trim();
                    optimizePath(machineId);
                    break;
                case 3:
                    return;
                default:
                    System.out.println("无效选项!");
            }

        } catch (NumberFormatException e) {
            System.out.println("请输入有效的数字选项!");
        }
    }


    private void listMachines() {
        List<IMachine> machines = new ArrayList<>(machineFactory.getAllMachines().values());
        System.out.println("\n—————— 设备列表 (总数: " + machines.size() + ") ——————");
        for (IMachine machine : machines) {
            System.out.println(String.format("ID=%s, 类型=%s, 状态=%s, 位置=%s",
                    machine.getMachineId(),
                    machine.getType(),
                    machine.getState().getDescription(),
                    machine.getPosition()));
        }
    }


    private void startMachine(String machineId) {
        IMachine machine = machineFactory.getMachine(machineId);
        if (machine != null) {
            machine.start();
            System.out.println("农机 " + machineId + " 已启动");
        } else {
            System.out.println("找不到农机: " + machineId);
        }
    }


    private void stopMachine(String machineId) {
        IMachine machine = machineFactory.getMachine(machineId);
        if (machine != null) {
            machine.stop();
            System.out.println("农机 " + machineId + " 已停止");
        } else {
            System.out.println("找不到农机: " + machineId);
        }
    }


    private void displaySystemStatus() {
        UserSession session = userManager.getCurrentSession();
        String username = session != null ? session.getUsername() : "无";
        String role = session != null ? session.getRole().getDescription() : "无";

        System.out.println(String.format("\n—————— 系统状态 ——————"));
        System.out.println(String.format("运行时间: %d秒", systemMonitor.getUptime()));
        System.out.println(String.format("当前用户: %s (%s)", username, role));
        System.out.println(String.format("农机数量: %d", machineFactory.getAllMachines().values().size()));
        System.out.println(String.format("安全事件: %d", safetyManager.getEventHistory().size()));
    }


    public void shutdown() {
        logger.info("AgriculturalSystem", "农业机械智能系统关闭中...");

        // 关闭系统各组件
        systemMonitor.shutdown();

        // 关闭日志记录器
        logger.shutdown();

        System.out.println("系统已安全关闭");
    }


    public static void main(String[] args) {
        AgriculturalSystem system = new AgriculturalSystem();

        try {
            system.initialize();
            system.start();
        } catch (Exception e) {
            System.err.println("系统发生严重错误: " + e.getMessage());
            e.printStackTrace();
        } finally {
            system.shutdown();
        }
    }


    private void addMachine(String type, String description) {
        if (!userManager.hasPermission(UserRole.OPERATOR)) {
            System.out.println("权限不足，需要操作员或管理员权限");
            return;
        }

        try {
            IMachineProxy proxy = proxyFactory.createMachineProxy(type);
            IMachine machine = proxy.getMachine();
            System.out.println(String.format("已添加农机: ID=%s, 类型=%s, 描述=%s",
                    machine.getMachineId(), type, description));
        } catch (Exception e) {
            System.out.println("添加农机失败: " + e.getMessage());
        }
    }


    private void setPathStrategy(String strategy) {
        if (!userManager.hasPermission(UserRole.OPERATOR)) {
            System.out.println("权限不足，需要操作员或管理员权限");
            return;
        }

        try {
            pathOptimizer.setPathStrategy(strategy);
            System.out.println("路径策略已设置为: " + strategy);
        } catch (Exception e) {
            System.out.println("设置路径策略失败: " + e.getMessage());
        }
    }


    private void executeTask(String machineId, String taskDescription) {
        if (!userManager.hasPermission(UserRole.OPERATOR)) {
            System.out.println("权限不足，需要操作员或管理员权限");
            return;
        }

        IMachine machine = machineFactory.getMachine(machineId);
        if (machine != null) {
            TaskCommand command = new MachineTaskCommand(machine, taskDescription);
            taskManager.executeCommand(command);
            System.out.println("任务已分配: " + taskDescription + " 到农机: " + machineId);
        } else {
            System.out.println("找不到农机: " + machineId);
        }
    }


    private void listTasks() {
        List<TaskCommand> activeTasks = taskManager.getActiveCommands();
        System.out.println("\n—————— 当前活动任务 (总数: " + activeTasks.size() + ") ——————");
        for (int i = 0; i < activeTasks.size(); i++) {
            System.out.println("任务 " + (i + 1) + ": " + activeTasks.get(i).getDescription());
        }
    }


    private void undoLastTask() {
        if (!userManager.hasPermission(UserRole.OPERATOR)) {
            System.out.println("权限不足，需要操作员或管理员权限");
            return;
        }

        taskManager.undoLastCommand();
    }


    private void emergencyStop(String machineId) {
        IMachine machine = machineFactory.getMachine(machineId);
        if (machine != null) {
            machine.setEmergencyStop(true);
            System.out.println("农机 " + machineId + " 已紧急停止");
        } else {
            System.out.println("找不到农机: " + machineId);
        }
    }


    private void releaseEmergencyStop(String machineId) {
        if (!userManager.hasPermission(UserRole.OPERATOR)) {
            System.out.println("权限不足，需要操作员或管理员权限");
            return;
        }

        IMachine machine = machineFactory.getMachine(machineId);
        if (machine != null) {
            machine.setEmergencyStop(false);
            System.out.println("农机 " + machineId + " 已解除紧急停止");
        } else {
            System.out.println("找不到农机: " + machineId);
        }
    }


    private void monitorEnvironment(Scanner scanner) {
        showEnvironmentMonitorMenu(scanner);
    }


    private void showEnvironmentMonitorMenu(Scanner scanner) {
        System.out.println("\n—————— 环境监测菜单 ——————");
        System.out.println("1. 查看当前环境数据");
        System.out.println("2. 手动更新环境数据");
        System.out.println("3. 启动自动环境监测");
        System.out.println("4. 停止自动环境监测");
        System.out.println("5. 启用农机自动响应");
        System.out.println("6. 禁用农机自动响应");
        System.out.println("7. 查看农机间通信日志");
        System.out.println("8. 查看当前路径策略状态");
        System.out.println("9. 返回主菜单");
        System.out.print("请选择: ");

        try {
            int choice = Integer.parseInt(scanner.nextLine().trim());

            switch (choice) {
                case 1:
                    displayCurrentEnvironmentData();
                    break;
                case 2:
                    updateEnvironmentDataManually(scanner);
                    break;
                case 3:
                    startAutoEnvironmentMonitoring(scanner);
                    break;
                case 4:
                    stopAutoEnvironmentMonitoring();
                    break;
                case 5:
                    enableMachineAutoOperation();
                    break;
                case 6:
                    disableMachineAutoOperation();
                    break;
                case 7:
                    viewCommunicationLogs();
                    break;
                case 8:
                    displayPathStrategyStatus();
                    break;
                case 9:
                    return;
                default:
                    System.out.println("无效选项!");
            }

        } catch (NumberFormatException e) {
            System.out.println("请输入有效的数字选项!");
        }
    }


    private void displayCurrentEnvironmentData() {
        EnvironmentData data = EnvironmentMonitor.getInstance().getEnvironmentData();

        System.out.println("\n—————— 当前环境数据 ——————");
        System.out.println(String.format("土壤湿度: %.1f%%", data.getSoilMoisture()));
        System.out.println(String.format("土壤pH值: %.1f", data.getSoilPH()));
        System.out.println("土壤养分: " + data.getSoilNutrients());
        System.out.println(String.format("温度: %.1f℃", data.getTemperature()));
        System.out.println(String.format("湿度: %.1f%%", data.getHumidity()));
        System.out.println(String.format("风速: %.1fm/s", data.getWindSpeed()));
        System.out.println("作物生长状态: " + data.getCropStatus());

        if (data.isObstacleDetected()) {
            System.out.println("警告: 检测到障碍物: " + data.getObstacleType());
        }

        System.out.println("\n—————— 环境适宜性评估 ——————");
        System.out.println("适合播种: " + (data.isSuitableForSeeding() ? "是" : "否"));
        System.out.println("适合喷洒: " + (data.isSuitableForSpraying() ? "是" : "否"));
        System.out.println("适合收割: " + (data.isSuitableForHarvesting() ? "是" : "否"));
        System.out.println("推荐路径策略: " + data.determineBestPathStrategy());
    }


    private void updateEnvironmentDataManually(Scanner scanner) {
        try {
            System.out.print("请输入土壤湿度 (20-80%): ");
            double soilMoisture = Double.parseDouble(scanner.nextLine().trim());

            System.out.print("请输入土壤pH值 (5.5-8.5): ");
            double soilPH = Double.parseDouble(scanner.nextLine().trim());

            System.out.print("请输入土壤养分 (丰富/一般/贫瘠): ");
            String soilNutrients = scanner.nextLine().trim();

            System.out.print("请输入温度 (15-40℃): ");
            double temperature = Double.parseDouble(scanner.nextLine().trim());

            System.out.print("请输入湿度 (30-90%): ");
            double humidity = Double.parseDouble(scanner.nextLine().trim());

            System.out.print("请输入风速 (0-10m/s): ");
            double windSpeed = Double.parseDouble(scanner.nextLine().trim());

            System.out.print("请输入作物生长状态 (良好/一般/需要关注): ");
            String cropStatus = scanner.nextLine().trim();

            System.out.print("是否有障碍物 (是/否): ");
            boolean obstacleDetected = "是".equals(scanner.nextLine().trim());

            String obstacleType = "";
            if (obstacleDetected) {
                System.out.print("请输入障碍物类型: ");
                obstacleType = scanner.nextLine().trim();
            }

            // 更新环境数据
            EnvironmentMonitor.getInstance().setEnvironmentData(
                    soilMoisture, soilPH, soilNutrients, temperature,
                    humidity, windSpeed, cropStatus, obstacleDetected, obstacleType
            );

            System.out.println("环境数据已手动更新");

        } catch (NumberFormatException e) {
            System.out.println("请输入有效的数值!");
        }
    }


    private void startAutoEnvironmentMonitoring(Scanner scanner) {
        try {
            System.out.print("请输入监测间隔 (秒): ");
            int interval = Integer.parseInt(scanner.nextLine().trim());

            if (interval < 5) {
                interval = 5; // 最小5秒
            }

            EnvironmentMonitor.getInstance().startAutoMonitoring(interval);
            System.out.println("自动环境监测已启动，间隔: " + interval + "秒");

        } catch (NumberFormatException e) {
            System.out.println("请输入有效的数字!");
        }
    }


    private void stopAutoEnvironmentMonitoring() {
        EnvironmentMonitor.getInstance().stopAutoMonitoring();
        System.out.println("自动环境监测已停止");
    }


    private void enableMachineAutoOperation() {
        Collection<IMachine> machines = machineFactory.getAllMachines().values();

        System.out.println("\n—————— 开始启用农机自动响应模式 ——————");
        int count = 0;
        for (IMachine machine : machines) {
            if (machine instanceof AbstractMachine) {
                AbstractMachine abstractMachine = (AbstractMachine) machine;
                abstractMachine.enableAutoOperation();
                System.out.println("农机 " + machine.getMachineId() +
                    " (类型: " + machine.getType() + ") - 已启用自动响应");
                count++;
            }
        }

        System.out.println("\n—————— 自动响应功能激活完成 ——————");
        System.out.println("共激活 " + count + " 台农机的自动响应功能");
        System.out.println("\n自动响应模式下，农机将:");
        System.out.println("1. 检测到障碍物时自动切换到避障策略并通知其他农机");
        System.out.println("2. 土壤湿度超过65%时自动切换到地形优化策略");
        System.out.println("3. 环境良好时自动使用直线策略");
        System.out.println("4. 根据环境数据自动调整作业参数（速度、深度等）");
        System.out.println("\n提示: 使用\"查看当前路径策略状态\"选项可随时查看当前系统使用的策略");
        System.out.println("提示: 请先启动农机，只有运行中的农机才会自动响应环境变化");
    }


    private void disableMachineAutoOperation() {
        Collection<IMachine> machines = machineFactory.getAllMachines().values();

        for (IMachine machine : machines) {
            if (machine instanceof AbstractMachine) {
                AbstractMachine abstractMachine = (AbstractMachine) machine;
                abstractMachine.disableAutoOperation();
            }
        }

        System.out.println("已为所有农机禁用自动响应模式");
    }


    private void viewCommunicationLogs() {
        List<Message> messageHistory = MessageBroker.getInstance().getMessageHistory();

        System.out.println("\n—————— 农机通信日志 (" + messageHistory.size() + " 条) ——————");
        for (Message message : messageHistory) {
            System.out.println(message.toString());
        }

        if (messageHistory.isEmpty()) {
            System.out.println("暂无通信记录");
        }
    }


    private void updateMachinePosition(String machineId, double x, double y) {
        if (!userManager.hasPermission(UserRole.OPERATOR)) {
            System.out.println("权限不足，需要操作员或管理员权限");
            return;
        }

        IMachine machine = machineFactory.getMachine(machineId);
        if (machine != null) {
            machine.updatePosition(x, y);
            System.out.println(String.format("农机 %s 位置已更新到 (%.2f, %.2f)", machineId, x, y));
        } else {
            System.out.println("找不到农机: " + machineId);
        }
    }


    private void optimizePath(String machineId) {
        IMachine machine = machineFactory.getMachine(machineId);
        if (machine == null) {
            System.out.println("找不到农机: " + machineId);
            return;
        }

        // 创建路径点
        PathPoint start = new PathPoint(machine.getCurrentX(), machine.getCurrentY());
        PathPoint end = new PathPoint(start.x + 200, start.y + 200);

        // 创建路径
        List<PathPoint> originalPath = new ArrayList<>();
        originalPath.add(start);
        originalPath.add(end);

        // 创建地形数据
        Random random = new Random();
        TerrainData terrain = new TerrainData(
                1000, 1000,
                random.nextDouble() * 20,  // 坡度 0-20
                30 + random.nextDouble() * 50,  // 湿度 30-80%
                random.nextDouble() > 0.5 ? "坚硬" : "松软"  // 土壤类型
        );

        // 优化路径
        String strategyName = pathOptimizer.getCurrentPathStrategy().getName();
        System.out.println("使用 " + strategyName + " 策略优化农机 " + machineId + " 的路径");
        List<PathPoint> optimizedPath = pathOptimizer.optimizePath(machineId, originalPath, terrain, new ArrayList<>());

        System.out.println("路径优化完成，生成了 " + optimizedPath.size() + " 个路径点");
        System.out.println("起点: " + start + ", 终点: " + end);
    }


    private void listSafetyEvents() {
        List<SafetyEvent> events = safetyManager.getEventHistory();
        System.out.println("\n—————— 安全事件历史记录 (总数: " + events.size() + ") ——————");
        for (int i = 0; i < events.size(); i++) {
            SafetyEvent event = events.get(i);
            System.out.println(String.format("事件 %d: 类型=%s, 农机=%s, 描述=%s, 已处理=%s",
                    i + 1, event.getEventType(), event.getMachineId(),
                    event.getDescription(), event.isHandled() ? "是" : "否"));
        }

        List<SafetyEvent> unhandled = safetyManager.getUnhandledEvents();
        if (!unhandled.isEmpty()) {
            System.out.println("警告: 有 " + unhandled.size() + " 个未处理的安全事件");
        }
    }


    private void simulateEmergency(String machineId, String type, String description) {
        if (!userManager.hasPermission(UserRole.OPERATOR)) {
            System.out.println("权限不足，需要操作员或管理员权限");
            return;
        }

        // 验证事件类型
        if (!type.equals("OBSTACLE") && !type.equals("FAULT") && !type.equals("EMERGENCY")) {
            System.out.println("无效的事件类型，支持的类型: OBSTACLE, FAULT, EMERGENCY");
            return;
        }

        // 创建适当的事件数据
        String eventData;
        switch (type) {
            case "OBSTACLE":
                eventData = "LARGE_ROCK";
                break;
            case "FAULT":
                eventData = "MODERATE";
                break;
            case "EMERGENCY":
                eventData = "BOUNDARY";
                break;
            default:
                eventData = "UNKNOWN";
        }

        // 创建安全事件
        SafetyEvent event = new SafetyEvent(machineId, type, eventData, description);
        System.out.println("模拟紧急情况: " + type + ", 农机: " + machineId);

        // 处理事件
        safetyManager.handleSafetyEvent(event);
    }


    private void listUsers() {
        if (!userManager.hasPermission(UserRole.ADMIN)) {
            System.out.println("权限不足，需要管理员权限");
            return;
        }

        List<User> users = userManager.getAllUsers();
        System.out.println("\n—————— 系统用户列表 (总数: " + users.size() + ") ——————");
        for (User user : users) {
            System.out.println(String.format("用户: %s, 角色: %s",
                    user.getUsername(), user.getRole().getDescription()));
        }
    }


    private void addUser(String username, String password, String role) {
        if (!userManager.hasPermission(UserRole.ADMIN)) {
            System.out.println("权限不足，需要管理员权限");
            return;
        }

        UserRole userRole;
        try {
            userRole = UserRole.valueOf(role.toUpperCase());
        } catch (IllegalArgumentException e) {
            System.out.println("无效的角色，支持的角色: ADMIN, OPERATOR, VIEWER");
            return;
        }

        boolean success = userManager.createUser(username, password, userRole);
        if (success) {
            System.out.println("用户添加成功: " + username);
        }
    }


    private void changeUserRole(String username, String role) {
        if (!userManager.hasPermission(UserRole.ADMIN)) {
            System.out.println("权限不足，需要管理员权限");
            return;
        }

        UserRole userRole;
        try {
            userRole = UserRole.valueOf(role.toUpperCase());
        } catch (IllegalArgumentException e) {
            System.out.println("无效的角色，支持的角色: ADMIN, OPERATOR, VIEWER");
            return;
        }

        boolean success = userManager.changeRole(username, userRole);
        if (success) {
            System.out.println("用户角色修改成功: " + username + " -> " + userRole.getDescription());
        }
    }


    private void showSystemManagementMenu(Scanner scanner) {
        System.out.println("\n—————— 系统管理 ——————");
        System.out.println("1. 查看系统状态");
        System.out.println("2. 日志管理");
        System.out.println("3. 返回主菜单");
        System.out.print("请选择: ");

        try {
            int choice = Integer.parseInt(scanner.nextLine().trim());

            switch (choice) {
                case 1:
                    displaySystemStatus();
                    break;
                case 2:
                    manageSystemLogs(scanner);
                    break;
                case 3:
                    return;
                default:
                    System.out.println("无效选项!");
            }

        } catch (NumberFormatException e) {
            System.out.println("请输入有效的数字选项!");
        }
    }


    private void manageSystemLogs(Scanner scanner) {
        System.out.println("\n—————— 日志管理 ——————");
        System.out.println("1. 设置日志级别");
        System.out.println("2. 查看最近日志");
        System.out.println("3. 返回上级菜单");
        System.out.print("请选择: ");

        try {
            int choice = Integer.parseInt(scanner.nextLine().trim());

            switch (choice) {
                case 1:
                    if (!userManager.hasPermission(UserRole.ADMIN)) {
                        System.out.println("权限不足，需要管理员权限");
                        return;
                    }

                    System.out.println("可用日志级别: DEBUG, INFO, WARN, ERROR");
                    System.out.print("请输入新的日志级别: ");
                    String level = scanner.nextLine().trim().toUpperCase();

                    try {
                        LogLevel logLevel = LogLevel.valueOf(level);
                        logger.setLogLevel(logLevel);
                        System.out.println("日志级别已设置为: " + logLevel);
                    } catch (IllegalArgumentException e) {
                        System.out.println("无效的日志级别!");
                    }
                    break;
                case 2:
                    // 仅显示日志信息的简单实现
                    System.out.println("系统日志功能已启用");
                    System.out.println("当前日志文件路径: system_logs.txt");
                    System.out.println("注意: 完整日志已存储到系统日志文件中");
                    break;
                case 3:
                    return;
                default:
                    System.out.println("无效选项!");
            }

        } catch (NumberFormatException e) {
            System.out.println("请输入有效的数字选项!");
        }
    }


    private void displayPathStrategyStatus() {
        String currentStrategy = pathOptimizer.getCurrentPathStrategy().getName();

        System.out.println("\n—————— 当前路径策略状态 ——————");
        System.out.println("当前使用的策略: " + currentStrategy);


        String description = "";
        switch (currentStrategy) {
            case "direct":
                description = "直线策略 - 直接从起点到终点，路径最短，适用于无障碍物的良好环境";
                break;
            case "avoidObstacle":
                description = "避障策略 - 绕过障碍物，保证安全，适用于有障碍物的环境";
                break;
            case "terrainOptimized":
                description = "基于农田状况优化策略 - 根据地形选择最佳路径，适用于土壤湿度高或地形复杂的环境";
                break;
            default:
                description = "未知策略";
        }
        System.out.println("策略说明: " + description);


        boolean anyAutoEnabled = false;
        System.out.println("\n农机自动响应状态:");
        Collection<IMachine> machines = machineFactory.getAllMachines().values();
        for (IMachine machine : machines) {
            if (machine instanceof AbstractMachine) {
                AbstractMachine abstractMachine = (AbstractMachine) machine;
                boolean autoEnabled = abstractMachine.isAutoOperationEnabled();
                System.out.println("农机 " + machine.getMachineId() +
                        " (" + machine.getType() + "): " +
                        (autoEnabled ? "已启用自动响应" : "未启用自动响应"));
                if (autoEnabled) {
                    anyAutoEnabled = true;
                }
            }
        }


        if (anyAutoEnabled) {
            System.out.println("\n提示: 至少有一台农机已启用自动响应，环境变化时将自动切换路径策略");
            System.out.println("      检测到障碍物时将切换到避障策略");
            System.out.println("      土壤湿度高于65%时将切换到基于农田状况优化策略");
        } else {
            System.out.println("\n提示: 所有农机均未启用自动响应，环境变化时不会自动切换路径策略");
            System.out.println("      请使用\"启用农机自动响应\"选项启用自动响应功能");
        }
    }
} 